package net.p2pcdn.controller;

import com.qc.bean.result.ResponseData;
import net.p2pcdn.core.order.domain.PayType;
import net.p2pcdn.core.order.domain.PlatformEnum;
import net.p2pcdn.core.order.service.OrderService;
import net.p2pcdn.core.product.domain.Product;
import net.p2pcdn.core.product.service.ProductCreateCommand;
import net.p2pcdn.core.product.service.ProductService;
import net.p2pcdn.user.domain.User;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.swing.text.PlainDocument;
import java.math.BigDecimal;

/**
 * @author zx
 */
@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;

    @PostMapping("/save")
    public ResponseData saveProduct(ProductCreateCommand command) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        command.setCreator(user.getId());
        int id = productService.saveProduct(command);
        return ResponseData.success(id);
    }

    @GetMapping("/{id}")
    public ResponseData getProduct(@PathVariable("id") int id) {
        return ResponseData.success(productService.getProduct(id));
    }

    @PostMapping("/{id}/status")
    public ResponseData getProduct(@PathVariable("id") int id, int status) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        productService.publishProduct(user.getId(), id, status);
        return ResponseData.success("ok");
    }

    @PostMapping("/q")
    public ResponseData query(String name, String serial, Integer status, Integer type, int page, int size) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        return ResponseData.success(productService.query(name, serial, status, type, page, size));
    }


    @PostMapping("/{id}/purchase")
    public ResponseData getProduct(@PathVariable("id") int id, String email, BigDecimal actualPayment,String domains,String remark,int amount) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        orderService.openTrafficPackageService(user.getId(),email,id,actualPayment,domains, PayType.OFFLINE, PlatformEnum.UNKNOWN,remark,amount);
        return ResponseData.success("ok");
    }
}
